package com.my.study.bean;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author: yidujun
 * @create: 2021/03/23 16:18
 */
public class PropertyEditorSample {

    public static Node convert(Map<String, String> parameters) throws Exception{
        Node node = new Node();
        // 注册bean的编辑器，放在WeakCacheMap中
        PropertyEditorManager.registerEditor(User.class, UserEditor.class);
        BeanInfo bi = Introspector.getBeanInfo(Node.class);
        // 获取所有属性
        PropertyDescriptor[] pds = bi.getPropertyDescriptors();
        for (PropertyDescriptor pd : pds) {
            Class<?> propertyType = pd.getPropertyType();
            Method writeMethod = pd.getWriteMethod();
            if (propertyType == Class.class) {
                //
            } else if (propertyType == String.class) {
                writeMethod.invoke(node, parameters.get(pd.getName()));
            } else {
                //根据类型查找bean的编辑器,获取到了UserEditor的实例
                PropertyEditor editor = PropertyEditorManager.findEditor(propertyType);
                if (editor != null) {
                    editor.setAsText(parameters.get(pd.getName()));
                    writeMethod.invoke(node, editor.getValue());
                } else {
                    System.out.println("no editor for:"+pd.getName());
                }
            }
        }

        return node;
    }


}
